package cn.lingxue.lingapi.config;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 客户端IP地址工具类
 *
 * @author 多仔ヾ
 */
public class ClientipUtil {

    /**
     * 获取客户端请求IP
     *
     * @author 多仔ヾ
     * @return 客户端请求IP
     **/
    public static String getClientip() {
        HttpServletRequest httpServerRequest = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        String clientip = httpServerRequest.getHeader("x-forwarded-for");
        if (clientip == null || clientip.length() == 0 || "unknown".equalsIgnoreCase(clientip)) {
            clientip = httpServerRequest.getHeader("Proxy-Client-IP");
        }
        if (clientip == null || clientip.length() == 0 || "unknown".equalsIgnoreCase(clientip)) {
            clientip = httpServerRequest.getHeader("WL-Proxy-Client-IP");
        }
        if (clientip == null || clientip.length() == 0 || "unknown".equalsIgnoreCase(clientip)) {
            clientip = httpServerRequest.getHeader("HTTP_CLIENT_IP");
        }
        if (clientip == null || clientip.length() == 0 || "unknown".equalsIgnoreCase(clientip)) {
            clientip = httpServerRequest.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (clientip == null || clientip.length() == 0 || "unknown".equalsIgnoreCase(clientip)) {
            clientip = httpServerRequest.getRemoteAddr();
        }

        if (clientip != null && clientip.length() > 15) {
            if (clientip.indexOf(',') > 0) {
                clientip = clientip.substring(0, clientip.indexOf(','));
            }
        }

        if ("localhost".equalsIgnoreCase(clientip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(clientip)){
            clientip = "127.0.0.1";
        }

        return clientip;
    }

    /**
     * 获取IP归属地信息
     *
     * @author 多仔ヾ
     * @param ip 请求IP
     * @return IP归属地信息
     **/
    public static String getRealAddres(String ip) {
        if (StrUtil.isBlank(ip)) {
            return "未知";
        }

        if (NetUtil.isInnerIP(ip)) {
            return "内网IP";
        }

        try {
            String respStr = HttpUtil.createGet("https://nestapi.fjisp.com/clientipAddress.query?ip=" + ip)
                    .execute()
                    .body();
            if (StrUtil.isEmpty(respStr)) {
                return "未知";
            }

            return JSONUtil.parseObj(respStr).getStr("address");
        } catch (Exception ex) {
            return "未知";
        }
    }

}
